#!/usr/bin/env python3
import os
import json
import requests
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def fetch_new_addresses():
    """从多个源获取新的以太坊地址"""
    addresses = set()
    
    # 从Etherscan获取地址
    try:
        # 这里需要添加您的Etherscan API密钥
        api_key = os.getenv('ETHERSCAN_API_KEY')
        if api_key:
            response = requests.get(
                f'https://api.etherscan.io/api?module=account&action=txlist&address=0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe&startblock=0&endblock=99999999&sort=asc&apikey={api_key}'
            )
            if response.status_code == 200:
                data = response.json()
                if data['status'] == '1':
                    for tx in data['result']:
                        addresses.add(tx['from'].lower())
                        addresses.add(tx['to'].lower())
    except Exception as e:
        logger.error(f"从Etherscan获取地址失败: {e}")

    return addresses

def update_address_files(new_addresses):
    """更新地址文件"""
    # 更新txt文件
    with open('addresses.txt', 'r') as f:
        existing_addresses = set(line.strip().lower() for line in f if line.strip() and not line.startswith('#'))
    
    all_addresses = existing_addresses.union(new_addresses)
    
    with open('addresses.txt', 'w') as f:
        f.write(f"# 以太坊地址库\n")
        f.write(f"# 最后更新: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"# 格式: 每行一个地址，可以包含0x前缀\n\n")
        for addr in sorted(all_addresses):
            f.write(f"{addr}\n")
    
    # 更新json文件
    addresses_data = {
        "last_update": datetime.now().isoformat(),
        "total_addresses": len(all_addresses),
        "addresses": list(all_addresses)
    }
    
    with open('addresses.json', 'w') as f:
        json.dump(addresses_data, f, indent=2)

def main():
    """主函数"""
    try:
        logger.info("开始更新地址库...")
        new_addresses = fetch_new_addresses()
        if new_addresses:
            update_address_files(new_addresses)
            logger.info(f"成功更新地址库，新增 {len(new_addresses)} 个地址")
        else:
            logger.info("没有新的地址需要更新")
    except Exception as e:
        logger.error(f"更新地址库时出错: {e}")

if __name__ == "__main__":
    main() 